<?php
/**
 * This is the template for generating a CRUD controller class file.
 */

use yii\db\ActiveRecordInterface;
use yii\helpers\StringHelper;


/* @var $this yii\web\View */
/* @var $generator backend\modules\giitpl\generators\crud\Generator */

$controllerID = $generator->getControllerID();
$controllerClass = StringHelper::basename($generator->controllerClass);
$modelClass = StringHelper::basename($generator->modelClass);
$searchModelClass = StringHelper::basename($generator->searchModelClass);
if ($modelClass === $searchModelClass) {
    $searchModelAlias = $searchModelClass . 'Search';
}

/* @var $class ActiveRecordInterface */
$class = $generator->modelClass;
$pks = $class::primaryKey();
$urlParams = $generator->generateUrlParams();
$actionParams = $generator->generateActionParams();
$actionParamComments = $generator->generateActionParamComments();

$namespaceStr = StringHelper::dirname(ltrim($generator->controllerClass, '\\'));
$arr = explode("\\", $namespaceStr);
$moduleId = '';
foreach ($arr as $key => $item) {
    if ($item == 'controllers') {
        $moduleId = isset($arr[$key - 1]) ? $arr[$key - 1] : '';
        break;
    }
}

$tags = $generator->doc;
echo "<?php\n";
?>

namespace <?= StringHelper::dirname(ltrim($generator->controllerClass, '\\')) ?>;

use Yii;
use <?= ltrim($generator->modelClass, '\\') ?>;
<?php if (!empty($generator->searchModelClass)): ?>
use <?= ltrim($generator->searchModelClass, '\\') . (isset($searchModelAlias) ? " as $searchModelAlias" : "") ?>;
<?php else: ?>
use yii\data\ActiveDataProvider;
<?php endif; ?>
use <?= ltrim($generator->baseControllerClass, '\\') ?>;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * @author  wsl <wsl_ys@163.com>
 * @OA\Tag(
 *     name="<?= $tags ?>",
 *     description="<?= $tags ?>接口文档",
 * )
 * <?= $controllerClass ?> implements the CRUD actions for <?= $modelClass ?> model.
 */
class <?= $controllerClass ?> extends <?= StringHelper::basename($generator->baseControllerClass) . "\n" ?>
{
    /**
     * Lists all <?= $modelClass ?> models.
     * @OA\Get(
     *     path="/<?= $moduleId ?>/<?= $controllerID ?>",
     *     tags={"<?= $tags ?>"},
     *     summary="列表",
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="no_page",
     *         in="path",
     *         description="不分页，此参数值为1时不分页"
     *     ),
     *     @OA\Response(
     *         response=403,
     *         description="无权访问"
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="响应结果",
     *         @OA\JsonContent(
     *             type="array",
     *             @OA\Items(ref="#/components/schemas/<?= $modelClass ?>")
     *         )
     *     )
     * )
     */
    public function actionIndex()
    {
<?php if (!empty($generator->searchModelClass)): ?>
        $params = Yii::$app->request->queryParams;

        $searchModel = new ArticleSearch($params);
        $dataProvider = $searchModel->search($params);

        return $this->success($searchModel->formatSearch($dataProvider));
<?php else: ?>
        $dataProvider = new ActiveDataProvider([
            'query' => <?= $modelClass ?>::find(),
        ]);

        return $this->success($searchModel->formatSearch($dataProvider));
<?php endif; ?>
    }

    /**
     * Displays a single <?= $modelClass ?> model.
     * <?= implode("\n     * ", $actionParamComments) . "\n" ?>
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     *
     * ==========================================================
     * @OA\Get (
     *     path="/<?= $moduleId ?>/<?= $controllerID ?>/{id}",
     *     tags={"<?= $tags ?>"},
     *     summary="<?= $modelClass ?>详细信息",
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         required=true,
     *         description="ID",
     *         @OA\Schema(
     *             type="integer",
     *             format="int64"
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="响应结果",
     *         @OA\JsonContent(ref="#/components/schemas/<?= $modelClass ?>"),
     *     )
     * )
     */
    public function actionView(<?= $actionParams ?>)
    {
        return $this->success($this->findModel($id));
    }

    /**
     * Creates a new <?= $modelClass ?> model.
     * @return mixed
     *
     * =================================================
     * @OA\Post (
     *     path="/<?= $moduleId ?>/<?= $controllerID ?>",
     *     tags={"<?= $tags ?>"},
     *     summary="添加<?= $modelClass ?>",
     *     security={{"bearerAuth":{}}},
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 ref="#/components/schemas/<?= $modelClass ?>"
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=403,
     *         description="无权访问"
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="响应结果",
     *         @OA\JsonContent(ref="#/components/schemas/<?= $modelClass ?>")
     *     )
     * )
     */
    public function actionCreate()
    {
        $model = new <?= $modelClass ?>();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->success($model);
        }

        $this->fail($model->getErrorMessage());
    }

    /**
     * Updates an existing <?= $modelClass ?> model.
     * <?= implode("\n     * ", $actionParamComments) . "\n" ?>
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     *
     * ==========================================================
     * @OA\Put (
     *     path="/<?= $moduleId ?>/<?= $controllerID ?>/{id}",
     *     tags={"<?= $tags ?>"},
     *     summary="更新",
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         required=true,
     *         description="ID",
     *         @OA\Schema(
     *             type="integer",
     *             format="int64"
     *         )
     *     ),
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 ref="#/components/schemas/<?= $modelClass ?>"
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=403,
     *         description="无权访问"
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="响应结果"
     *     )
     * )
     */
    public function actionUpdate(<?= $actionParams ?>)
    {
        $model = $this->findModel(<?= $actionParams ?>);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->success($model);
        }

        $this->fail($model->getErrorMessage());
    }

    /**
     * Deletes an existing <?= $modelClass ?> model.
     * <?= implode("\n     * ", $actionParamComments) . "\n" ?>
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     *
     * ==========================================================
     * @OA\Delete (
     *     path="/<?= $moduleId ?>/<?= $controllerID ?>/{id}",
     *     tags={"<?= $tags ?>"},
     *     summary="删除",
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         required=true,
     *         description="ID",
     *         @OA\Schema(
     *             type="integer",
     *             format="int64"
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK"
     *     )
     * )
     */
    public function actionDelete(<?= $actionParams ?>)
    {
        $this->findModel(<?= $actionParams ?>)->delete();

        $this->success('删除成功！');
    }

    /**
     * Finds the <?= $modelClass ?> model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * <?= implode("\n     * ", $actionParamComments) . "\n" ?>
     * @return <?=                   $modelClass ?> the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel(<?= $actionParams ?>)
    {
<?php
if (count($pks) === 1) {
    $condition = '$id';
} else {
    $condition = [];
    foreach ($pks as $pk) {
        $condition[] = "'$pk' => \$$pk";
    }
    $condition = '[' . implode(', ', $condition) . ']';
}
?>
        if (($model = <?= $modelClass ?>::findOne(<?= $condition ?>)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(<?= $generator->generateString('请的数据不存在.') ?>);
    }
}
